package com.lg.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author by Mr. Li 2020/12/13 1:33
 */
@Controller
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;


    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam String token) {
        return ((String) redisTemplate.opsForValue().get(token));
    }

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String redirectUrl, Model model,
                        @CookieValue(required = false, value = "sso_token") String ssoToken) {
        // 标记好请求登录的页面
        model.addAttribute("url", redirectUrl);

        //判断之前是否有人留下足迹
        if (!StringUtils.isEmpty(ssoToken)) {
            return "redirect:" + redirectUrl + "?token=" + ssoToken;
        }

        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String redirectUrl, HttpServletResponse response
    ) {


        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 登录成功，生成一个token  保存在redis 中
            String TOKEN = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(TOKEN, username);

            // 为了实现 单点服务器。在登录成功后必须在浏览器留下一个印记。用于其他未登录的系统，获取实现免登录
            Cookie cookie = new Cookie("sso_token", TOKEN);
            response.addCookie(cookie);
            return "redirect:" + redirectUrl + "?token=" + TOKEN;
        }
        return "login";
    }
}
